from flask import Flask, request, jsonify
from datetime import datetime, timedelta
import random
import json

app = Flask(__name__)

VILLAGES = [
    {"villageId": "1", "villageName": "阳光小区", "villageNumber": "V001", "detailedAddress": "北京市朝阳区阳光路1号", "status": 1, "onlineStatus": "在线"},
    {"villageId": "2", "villageName": "花园小区", "villageNumber": "V002", "detailedAddress": "北京市海淀区花园街2号", "status": 1, "onlineStatus": "在线"},
    {"villageId": "3", "villageName": "学府小区", "villageNumber": "V003", "detailedAddress": "北京市西城区学府路3号", "status": 2, "onlineStatus": "离线"},
    {"villageId": "4", "villageName": "绿地小区", "villageNumber": "V004", "detailedAddress": "北京市东城区绿地大道4号", "status": 3, "onlineStatus": "告警"},
]

DEVICES = {
    "V001": [
        {
            "deviceId": "121794",
            "deviceName": "供热设备A",
            "serialNumber": "SN001",
            "thingsModels": [
                {"modelId": "temp_01", "modelName": "温度", "value": 65.5, "unit": "℃", "type": 1},
                {"modelId": "pressure_01", "modelName": "压力", "value": 1.8, "unit": "MPa", "type": 1},
                {"modelId": "flow_01", "modelName": "流量", "value": 120.5, "unit": "m³/h", "type": 1},
            ]
        }
    ],
    "V002": [
        {
            "deviceId": "121795",
            "deviceName": "供热设备B",
            "serialNumber": "SN002",
            "thingsModels": [
                {"modelId": "temp_01", "modelName": "温度", "value": 70.2, "unit": "℃", "type": 1},
                {"modelId": "pressure_01", "modelName": "压力", "value": 1.5, "unit": "MPa", "type": 1},
                {"modelId": "flow_01", "modelName": "流量", "value": 110.3, "unit": "m³/h", "type": 1},
            ]
        }
    ],
    "V003": [
        {
            "deviceId": "121796",
            "deviceName": "供热设备C",
            "serialNumber": "SN003",
            "thingsModels": [
                {"modelId": "temp_01", "modelName": "温度", "value": 0, "unit": "℃", "type": 1},
                {"modelId": "pressure_01", "modelName": "压力", "value": 0, "unit": "MPa", "type": 1},
                {"modelId": "flow_01", "modelName": "流量", "value": 0, "unit": "m³/h", "type": 1},
            ]
        }
    ],
    "V004": [
        {
            "deviceId": "121797",
            "deviceName": "供热设备D",
            "serialNumber": "SN004",
            "thingsModels": [
                {"modelId": "temp_01", "modelName": "温度", "value": 85.3, "unit": "℃", "type": 1},
                {"modelId": "pressure_01", "modelName": "压力", "value": 2.2, "unit": "MPa", "type": 1},
                {"modelId": "flow_01", "modelName": "流量", "value": 95.7, "unit": "m³/h", "type": 1},
            ]
        }
    ],
}

def generate_time_series(start_time, end_time, model_id, base_value=65.0, variance=5.0):
    start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
    end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
    
    timestamps = []
    values = []
    
    current = start
    while current <= end:
        timestamps.append(current.strftime("%Y-%m-%d %H:%M:%S"))
        value = base_value + random.uniform(-variance, variance)
        values.append(round(value, 2))
        current += timedelta(minutes=5)
    
    return timestamps, values

def calculate_statistics(values):
    if not values:
        return {}
    
    sorted_values = sorted(values)
    n = len(values)
    
    mean = sum(values) / n
    variance = sum((x - mean) ** 2 for x in values) / n
    std_dev = variance ** 0.5
    
    q1 = sorted_values[n // 4]
    q2 = sorted_values[n // 2]
    q3 = sorted_values[3 * n // 4]
    
    return {
        "max": max(values),
        "min": min(values),
        "mean": round(mean, 2),
        "median": round(q2, 2),
        "std_dev": round(std_dev, 2),
        "variance": round(variance, 2),
        "q1": round(q1, 2),
        "q3": round(q3, 2),
        "iqr": round(q3 - q1, 2),
        "range": round(max(values) - min(values), 2),
        "data_points": n,
        "missing_count": 0,
        "missing_rate": 0.0
    }

@app.route('/ai/query/villages', methods=['GET'])
def query_villages():
    village_name = request.args.get('villageName')
    
    if village_name:
        filtered = [v for v in VILLAGES if village_name in v['villageName']]
        return jsonify({"code": 200, "msg": "success", "data": filtered})
    
    simple_list = [
        {
            "villageId": v["villageId"],
            "villageName": v["villageName"],
            "villageNumber": v["villageNumber"],
            "onlineStatus": v["onlineStatus"]
        }
        for v in VILLAGES
    ]
    return jsonify({"code": 200, "msg": "success", "data": simple_list})

@app.route('/ai/query/village/device/running', methods=['GET'])
def query_village_device_running():
    village_number = request.args.get('villageNumber')
    
    if not village_number:
        return jsonify({"code": 400, "msg": "缺少参数: villageNumber", "data": []})
    
    village = next((v for v in VILLAGES if v['villageNumber'] == village_number), None)
    if not village:
        return jsonify({"code": 404, "msg": "小区不存在", "data": []})
    
    devices = DEVICES.get(village_number, [])
    
    result = [{
        "villageName": village["villageName"],
        "villageId": village["villageId"],
        "devices": devices
    }]
    
    return jsonify({"code": 200, "msg": "success", "data": result})

@app.route('/ai/query/village/device/history', methods=['GET'])
def query_village_device_history():
    village_number = request.args.get('villageNumber')
    start_time = request.args.get('startTime')
    end_time = request.args.get('endTime')
    model_ids = request.args.getlist('modelId')
    
    if not all([village_number, start_time, end_time, model_ids]):
        return jsonify({"code": 400, "msg": "缺少必填参数", "data": []})
    
    village = next((v for v in VILLAGES if v['villageNumber'] == village_number), None)
    if not village:
        return jsonify({"code": 404, "msg": "小区不存在", "data": []})
    
    devices = DEVICES.get(village_number, [])
    if not devices:
        return jsonify({"code": 404, "msg": "该小区无设备", "data": []})
    
    device = devices[0]
    raw_data = {}
    statistical_features = {}
    
    base_values = {
        "temp_01": 65.0,
        "pressure_01": 1.8,
        "flow_01": 120.0
    }
    
    for model_id in model_ids:
        base_value = base_values.get(model_id, 50.0)
        timestamps, values = generate_time_series(start_time, end_time, model_id, base_value)
        
        model = next((m for m in device['thingsModels'] if m['modelId'] == model_id), None)
        unit = model['unit'] if model else ""
        
        raw_data[model_id] = {
            "model_id": model_id,
            "timestamps": timestamps,
            "values": values,
            "unit": unit,
            "data_points": len(values)
        }
        
        statistical_features[model_id] = calculate_statistics(values)
    
    result = [{
        "villageName": village["villageName"],
        "villageId": village["villageId"],
        "devices": [{
            "thingsModels": device["thingsModels"],
            "rawData": raw_data,
            "statisticalFeatures": statistical_features
        }]
    }]
    
    return jsonify({"code": 200, "msg": "success", "data": result})

@app.route('/ai/query/village/models', methods=['GET'])
def query_village_models():
    village_number = request.args.get('villageNumber')
    
    if not village_number:
        return jsonify({"code": 400, "msg": "缺少参数: villageNumber", "data": []})
    
    devices = DEVICES.get(village_number, [])
    if not devices:
        return jsonify({"code": 404, "msg": "该小区无设备", "data": []})
    
    models = [
        {"modelId": m["modelId"], "modelName": m["modelName"]}
        for m in devices[0]["thingsModels"]
    ]
    
    return jsonify({"code": 200, "msg": "success", "data": models})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5080, debug=True)
